package com.fresh.bus.chat.business;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.SortParameters.Order;
import org.springframework.data.redis.core.BulkMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.query.SortQuery;
import org.springframework.data.redis.core.query.SortQueryBuilder;
import org.springframework.stereotype.Component;

import com.fresh.bus.canoe.session.SessionRoleManager;
import com.fresh.bus.chat.persist.UserDao;

@Component
public class SelectService {
	private static final Logger log = LoggerFactory
			.getLogger(SelectService.class);
	@Resource
	private UserDao dao;

	@Resource
	private MessageService msgService;
	@Resource
	protected UserService userService;
	@Resource
	protected SessionRoleManager roleManager;

	private StringRedisTemplate template;

	@Autowired
	public SelectService(StringRedisTemplate template) {
		this.template = template;
	}

	public List<Map<String, String>> getLatestUsers(int index, String province,
			String sex) {
		
		int len = this.userService.areaGroup(province, sex).size();
		log.debug("the province:" + province + "'s length is " + len);
		
		String key = KeyUtils.areaGroup(province, sex);
		String pid = "uid:*->";
		final String pidKey = "#";
		final String sex2 = "sex";
		final String online = "online";
		final String content = "selfDesc";
		final String birthYear = "birthYear";
		final String location = "location";
		final String level = "level";

		SortQuery<String> query = SortQueryBuilder.sort(key).by("score")
				.order(Order.DESC).get(pidKey).get(pid + sex2)
				.get(pid + online).get(pid + content).get(pid + birthYear)
				.get(pid + location).get(pid + level).limit(index, index + 9)
				.build();
		log.debug(query.toString());
		BulkMapper<Map<String, String>, String> hm = new BulkMapper<Map<String, String>, String>() {
			@Override
			public Map<String, String> mapBulk(List<String> bulk) {
				Map<String, String> map = new LinkedHashMap<String, String>();
				Iterator<String> iterator = bulk.iterator();

				String uid = iterator.next();
				map.put("id", uid);
				map.put(sex2, iterator.next());
				map.put(online, iterator.next());
				map.put(content, iterator.next());
				map.put(birthYear, iterator.next());
				map.put(location, iterator.next());
				map.put(level, iterator.next());
				return map;
			}
		};
		List<Map<String, String>> sort = template.sort(query, hm);
		return sort;
	}
}
